package broadcast

import (
	"admin100/app/dao"
	"admin100/app/service/centerservice"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/utils"
	"encoding/json"
	"strings"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gcron"
	"github.com/gogf/gf/os/gtime"
)

var Broadcast = &broadcastService{}

type broadcastService struct{}

// 启动广播
func (s *broadcastService) StartNoticeLog(id int) bool {
	nlg, err := dao.NoticeLog.FindOne(dao.NoticeLog.Columns.Id, id)
	defErr.SelectRetPanic(err, nlg, define.DataOptFail)

	if dao.NoticeLog.GetIsNoticeClose(nlg) {
		defErr.Panic(define.NotcieEnded)
	}
	cronFun := func() {
		s.SendNoticeLog(nlg.Id)
	}
	if nlg.CronTimes > 0 {
		_, err := gcron.AddTimes(nlg.CronTimeStr, nlg.CronTimes, cronFun, dao.NoticeLog.GetCronName(nlg.Id))
		if err != nil {
			defErr.Panic(define.BroadcastErr, err.Error())
		}
	} else {
		_, err := gcron.Add(nlg.CronTimeStr, cronFun, dao.NoticeLog.GetCronName(nlg.Id))
		if err != nil {
			defErr.Panic(define.BroadcastErr, err.Error())
		}
	}

	return true
}

// 发送广播
func (s *broadcastService) SendNoticeLog(id int) {
	// defer func() {
	// 	gcron.Remove(dao.NoticeLog.GetCronName(id))
	// }()
	var (
		nodeSlice = []string{}
	)
	nlg, err := dao.NoticeLog.FindOne(dao.NoticeLog.Columns.Id, id)
	defErr.SelectRetPanic(err, nlg, define.DataOptFail)

	if nlg.IsAllServer == 0 {
		nlg.ServerIdList = strings.ReplaceAll(nlg.ServerIdList, "[", "")
		nlg.ServerIdList = strings.ReplaceAll(nlg.ServerIdList, "]", "")
		nlg.ServerIdList = strings.ReplaceAll(nlg.ServerIdList, "\"", "")

		nodeSlice = centerservice.CGameServer.FetchNodeSliceByPtIdAndSid(nlg.PlatformId, strings.Split(nlg.ServerIdList, ","))
	} else {
		nodeSlice = centerservice.CGameServer.FetchAllNodeByPlatId(nlg.PlatformId)
	}

	var request struct {
		NodeList []string `json:"nodeList"`
		Content  string   `json:"content"`
	}
	request.NodeList = nodeSlice
	request.Content = nlg.Content

	urls := centerservice.CGameNode.GetGameURLSliceByNode(nodeSlice, "/send_notice")
	for _, url := range urls {
		data, err := json.Marshal(request)
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}

		_ = utils.HttpRequest(url, string(data))
		g.Log().Debugf("发送公告成功 node: %v, id: %v", nodeSlice, nlg.Id)
	}

	nlg.LastSendTime = uint(gtime.Timestamp())
	nlg.SendTimes++

	if nlg.CronTimes > 0 && nlg.CronTimes <= nlg.SendTimes {
		nlg.Status = 1
	}

	_, err = dao.NoticeLog.FieldsEx("userName").Save(nlg)
	if err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}

}
